package org.example.sercurity;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.example.redis.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static org.example.common.Constants.CACHE_PREFIX_TOKEN;
@Component
public class TokenFilter extends OncePerRequestFilter {
    @Autowired
    private RedisUtils redisUtils;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("Access-Token");
        if(StringUtils.hasText(token)){
            //从redis中找回用户
            String json = redisUtils.get(CACHE_PREFIX_TOKEN + token);
            UserDeatilImpl userDetails = new ObjectMapper().readValue(json,UserDeatilImpl.class);
            //存储userDetails到ss的上下文中，以便ss鉴权使用
            UsernamePasswordAuthenticationToken authenticationToken
                    =new UsernamePasswordAuthenticationToken(userDetails,userDetails.getPassword(),userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }
        filterChain.doFilter(request,response);
    }

}
